package com.yunmaozj.easydb.common;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

/**
 * @author zhongminghong
 * @email yunmaozj@qq.com
 * @create 2018-05-25 7:34
 */
public class FileUtil {

    /**
     * 获取指定路径下的所有文件
     * @param packName
     * @param filter
     * @return
     */
    public static List<String> scan(String packName, FileFilter filter,boolean recursive){
        List<String> list = new ArrayList<String>();
        File file = new File(packName);
        if(!file.exists() || !file.isDirectory()){
            return list;
        }
        File[] files = (filter != null) ? file.listFiles(filter) : file.listFiles();
        for(File file1 : files){
            if(recursive && file1.isDirectory()){
                list.addAll(scan(file1.getAbsolutePath(),filter,recursive));
                continue;
            }
            list.add(file1.getPath());
        }
        return list;
    }

    public static List<String> scanClass(String packName,String pathName,FileFilter fileFilter,boolean recursive){
        List<String> list = new ArrayList<String>();
        File file = new File(pathName);
        if(!file.exists() || ! file.isDirectory()){
            return list;
        }
        File[] files = (fileFilter != null) ? file.listFiles(fileFilter) : file.listFiles();
        for(File file1 : files){
            if(recursive && file1.isDirectory()){
                list.addAll(scanClass(packName+"."+file1.getName(),file1.getAbsolutePath(),fileFilter,recursive));
                continue;
            }
            list.add(packName + "." + file1.getName().replace(".class",""));
        }
        return list;
    }

    public static List<Class<?>> getFileClass(String packName,String filepath){
        List<String> list = new ArrayList<String>();
        list.addAll(scanClass(packName, filepath, new FileFilter() {
            public boolean accept(File pathname) {
                return (pathname.isDirectory() || pathname.getName().endsWith(".class"));
            }
        }, true));
        List<Class<?>> classList = new ArrayList<Class<?>>();
        for(String className : list){
            try {
                Class<?> clazz = Class.forName(className);
                classList.add(clazz);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return classList;
    }
}
